<template>
	<view v-if="!isLogin" class="loginleftright">
		<view class="uni-flex uni-column">
			<view class="title">{{title}}</view>
		</view>
		<u-form :model="form" ref="uForm">
			<u-form-item label="账号" prop="username" label-width="100" required >
				<u-input v-model="form.username"  placeholder='请输入自己的大名' />
			</u-form-item>
			<u-form-item label="房间号" prop="roomid" label-width="100" required >
				<u-input v-model="form.roomid" placeholder='请输入房间号' />
			</u-form-item>
			<view class="btns">
				<u-button class="ubtn" @click="submit">进入</u-button>
			</view>
		</u-form>
	</view>
	<view v-else>
		<view v-if="!isVideoCall">
			<view v-for="(item, index) in users" :key="index">
				<view class="left">
					<text>名字：{{ item.name }} || 用户id： {{item.id}}</text>
				</view>
				<view v-if="item.id != this.userId" class="right">
					<button class="mini-btn" type="primary" size="mini" @click="handleStartCall(item.id, 'video')">视频</button>
					<button class="mini-btn" type="primary" size="mini" @click="handleStartCall(item.id, 'screen')">共享桌面</button>
				</view>
			</view>
		</view>
		<view v-else>
			<view>
			    <!-- <view class="big">
			    	<video id="remvideo"  autoPlay playsInline muted={{videoMuted}} >
			    		
			    	</video>
			    </view> --> 
				<view class="small">
					<video id="locvideo"  autoPlay playsInline muted={{videoMuted}} >
						
					</video>
			    </view>  
			    <view className="btn-tools">
			        
			    </view>     
			</view>
		</view>
	</view>
</template>

<script>
	import P2PVideoCall from '@/common/P2PVideoCall.js';
	export default {
		data() {
			return {
				title: '视频会议聊天demo',
				rules: {
					// 密码登陆账号校验，该输入可以是：手机号、邮箱、昵称
					username: [{
						validator: (rule, value, callback) => {
							return !this.$u.test.isEmpty(value)
						},
						message: '必填 * 输入内容不许为空',
						trigger: ['change', 'blur'],
					}],
					roomid: [{
						validator: (rule, value, callback) => {
							return !this.$u.test.isEmpty(value)
						},
						message: '必填 * 输入内容不许为空',
						trigger: ['change', 'blur'],
					}],
				},
				form: {
					username: '3',
					roomid: '3',
				},
				p2pVideoCall : null,
				users:[],
				userId:null,
				isVideoCall:false,
				isLogin:false,
				localStream:null,
				remoteStream:null,
				audioMuted:false,
				videoMuted:false,
				localVideo:'',
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			submit() {
				if (this.form.username == '' || this.form.roomid == ''){
					console.log(this.form,this.form.roomid);
					return;
				}
			    var p2pUrl = "wss://" + window.location.hostname + ":8000/ws";
			    var turnUrl = "/api/turn?service=turn&username=sample";
			    console.log("信令服务器地址:" + p2pUrl);
			    console.log("中转服务器地址:" + turnUrl);
			    this.p2pVideoCall = new P2PVideoCall(p2pUrl,turnUrl,this.form.username,this.form.roomid);
			    uni.$on('updateUserList',(users,self) => {
					this.isLogin = true;
					this.users = users;
					this.userId = self;
					console.log("users = " + JSON.stringify(this.users) + " userId=" + this.userId);
			    });
			
			    uni.$on('hangUp',(to,session) => {
			            this.isVideoCall=false;
			            this.localStream=null;
			            this.remoteStream=null;
			    });
			
			    uni.$on('leave',(to,session) => {
					this.isVideoCall=false;
					this.localStream=null;
					this.remoteStream=null;
			    });
			
			
			    uni.$on('newCall',(from,sessions) => {
			        this.isVideoCall = true;
			    });
			
			    uni.$on('localstream',(stream) => {
					this.isVideoCall = true;
			        this.localStream = stream;
					
					// const query = uni.createSelectorQuery().in(this);
					// this.localVideo = query.select('#locvideo');
					// console.log("2222uni on this.localVideo.." + this.localVideo);
					// console.log("3333uni on this.stream.." + stream);
					this.localVideo = document.querySelector('video');
					this.localVideo.srcObject = stream;
			    });
			
			    uni.$on('addstream',(stream) => {
			        this.remoteStream = stream;
			    });
			
			
			},
			
			handleStartCall(remoteUserId,type){
				this.isVideoCall = true;
			    this.p2pVideoCall.startCall(remoteUserId,type);
			},
			
			hangUp(){
			    this.p2pVideoCall.hangUp();
			},
			
			onVideoCLickHandler(){
			    let videoMuted = !this.videoMuted;
			    this.onToggleLocalVideoTrack(videoMuted);
				this.videoMuted = videoMuted;
			
			},
			
			onToggleLocalVideoTrack(muted){
			    var videoTracks = this.localStream.getVideoTracks();
			    if(videoTracks.length === 0){
			        console.log("没有本地视频");
			        return;
			    }
			    console.log("打开/关闭本地视频.");
			    for(var i = 0; i<videoTracks.length; ++i){
			        videoTracks[i].enabled = !muted;
			    }
			},
			
			onAudioClickHandler(){
			    let c = !this.audioMuted;
			    this.onToggleLocalAudioTrack(audioMuted);
				this.audioMuted = audioMuted;
			},
			
			onToggleLocalAudioTrack(muted){
			    var audioTracks = this.localStream.getAudioTracks();
			    if(audioTracks.length === 0){
			        console.log("没有本地音频");
			        return;
			    }
			    console.log("打开/关闭本地音频.");
			    for(var i = 0; i<audioTracks.length; ++i){
			        audioTracks[i].enabled = !muted;
			    }
			},
		}
	}
</script>

<style>
	.loginleftright{
		margin-left: 100rpx;
		margin-right: 100rpx;
	}
	.title {
		margin-top: 30rpx;
		font-size: 36rpx;
		color: #8f8f94;
		text-align: center;
	}
	
	.btns {
		margin-top: 20upx;
		text-align: center;
	
		.ubtn {
			display: inline-block;
			margin: 0 20upx;
		}
	}
	button {
	    margin-top: 30rpx;
	    margin-bottom: 30rpx;
	}
	
	.button-sp-area {
	    margin: 0 auto;
	    width: 60%;
	}
	
	.mini-btn {
	    margin-right: 10rpx;
	}
	
	.left{
	  display: flex;
	  align-items: center;
	  size:150px;
	  float: inherit;
	}
	.right{
	  display: flex;
	  align-items: center;
	}
	.big{
		position:'absolute';
		left:'0px';
		right:'0px';
		top:'0px';
		bottom:'0px';
		backgroundColor:'#323232';
		zIndex:0;
	}
	.small{
	    display:flex;
	    justifyContent: center;
	    alignItems:center;
	    width: 192px;
	   height: 108px;
	    bottom: 60px;
	    position: absolute;
	    
		borderStyle: solid;
		borderColor: #ffffff;
		overflow: hidden;
		zIndex: 99;
		borderRadius: 4px;
		right: 10px;
		borderWidth: 2px;
	}
</style>
